package com.spring.config;

import com.spring.ext.demos.ext.aop.LogBeforAdvice;
import com.spring.ext.demos.ext.aop.LogInterceptor;
import com.spring.ext.demos.web.BasicController;
import org.springframework.aop.framework.ProxyFactoryBean;
import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.aop.support.NameMatchMethodPointcutAdvisor;
import org.springframework.aop.support.RegexpMethodPointcutAdvisor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AopConfig {
    @Bean
    public LogBeforAdvice logBeforAdvice(){
        return  new LogBeforAdvice();
    }
    @Bean
    public LogInterceptor logInterceptor(){
        return new LogInterceptor();
    }
    @Bean
    public NameMatchMethodPointcutAdvisor nameMatchMethodPointcutAdvisor(){
        NameMatchMethodPointcutAdvisor na=new NameMatchMethodPointcutAdvisor();
        na.setAdvice(logInterceptor());
        na.setMappedName("test");
        return na;
    }

    /**
     * 通过bean进行代理
     * @return
     */
//    @Bean
//    public ProxyFactoryBean proxyFactoryBean(){
//        ProxyFactoryBean proxyFactoryBean = new ProxyFactoryBean();
//        proxyFactoryBean.setInterceptorNames("logBeforAdvice","logInterceptor");
//        proxyFactoryBean.setTargetClass(BasicController.class);
//        return proxyFactoryBean;
//    }

    /**
     * 通过方法名称进行代理
     * @return
     */
    @Bean
    public ProxyFactoryBean proxyFactoryBean(){
        ProxyFactoryBean proxyFactoryBean = new ProxyFactoryBean();
        proxyFactoryBean.setInterceptorNames("nameMatchMethodPointcutAdvisor");
        proxyFactoryBean.setTargetClass(BasicController.class);
        return proxyFactoryBean;
    }

    /**
     * 根据Bean名称自动代理
     * @return
     */
    @Bean
    public BeanNameAutoProxyCreator beanNameAutoProxyCreator(){
        BeanNameAutoProxyCreator beanNameAutoProxyCreator = new BeanNameAutoProxyCreator();
        beanNameAutoProxyCreator.setInterceptorNames("logBeforAdvice");
        beanNameAutoProxyCreator.setBeanNames("BasicController");
        return beanNameAutoProxyCreator;
    }

    /**
     * 通过正则匹配代理
     * @return
     */
    @Bean
    public RegexpMethodPointcutAdvisor regexpMethodPointcutAdvisor(){
        RegexpMethodPointcutAdvisor regexpMethodPointcutAdvisor = new RegexpMethodPointcutAdvisor();
        regexpMethodPointcutAdvisor.setAdvice(logBeforAdvice());
        regexpMethodPointcutAdvisor.setPattern("com.spring.ext.demos.web.*");
        return regexpMethodPointcutAdvisor;
    }


}
